home *** CD-ROM | disk | FTP | other *** search
/ NetNews Offline 2 / NetNews Offline Volume 2.iso / news / comp / lang / c++-part2 / 12167 < prev    next >
Encoding:
Internet Message Format  |  1996-08-05  |  1.8 KB

  1. Path: nrd.ups.com!nrd1rls
  2. From: nrd1rls@nrd.ups.com (Richard Siddall Contractor)
  3. Newsgroups: comp.lang.c++
  4. Subject: Re: Help: File counting lines
  5. Date: 18 Mar 1996 17:04:23 GMT
  6. Organization: United Parcel Service Research & Development
  7. Message-ID: <4ik52n$6ab@casey.nrd.ups.com>
  8. References: <4hni12$qst@bolivia.it.earthlink.net> <4huog1$t8s@news.axess.com>
  9. NNTP-Posting-Host: rufus.nrd.ups.com
  10. X-Newsreader: TIN [version 1.2 PL2]
  11.  
  12. Kamikaze (tdrymona@axess.com) wrote:
  13. : brunop@earthlink.net (Peter Bruno) wrote:
  14.  
  15. : >Does anyone have any suggestions on a fast way to count the number of lines in 
  16. : >a ASCII file.  Each line is terminted by a <enter> and all I need to do is 
  17. : >count the number of lines (records) in the file.
  18.  
  19. : >The way I've been doing it is by:  fgets(row, 128, File); count++;
  20. : >however, if the line is longer then 128 characters this does not work and it 
  21. : >would seem that there must be a better way of doing it anyway... perhaps by 
  22. : >incrementing the pointer until EOF??
  23.  
  24.     Your problem is that if fgets() reads a line longer than the buffer
  25.     you pass to it, it splits the line.  Therefore, you need to pass a
  26.     buffer longer than your longest line to fgets() if you wish to use
  27.     the number of fgets() calls as the count of lines.
  28.  
  29.     Alternately, you could check that the last character in the buffer
  30.     (before the string terminator) is a newline: if so, fgets() did not
  31.     split the line.
  32.  
  33.     The conventional was is to use fgetc() and examine each character so
  34.     see if it is a newline (the equivalent of Enter).
  35.  
  36. : Yeah use the stream objects, like this
  37.  
  38. : ifstream in;
  39. : int count = 0;
  40. : char buffer[BUFFER_SIZE );
  41.  
  42. : in = open( name_of_file );
  43. : if ( !in.bad() )
  44. : {
  45. :     while ( !in.eof() ) 
  46. :     {
  47. :     getline( buffer, sizeof( buffer ) );
  48. :     count++;
  49. :     }
  50. :     in.close();    
  51. : }
  52.  
  53.     This has the same problem as the fgets() approach.
  54.  
  55.     Just my 0.02 ECUs.
  56.  
  57.         Richard Siddall.
  58.